<?php

namespace app\admin\controller\coupon;

use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 优惠码管理
 *
 * @icon fa fa-user
 */
class Coupon extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,title,prefix';

    /**
     * @var \app\admin\model\Coupon
     */
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('coupon');
    
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where(array('status' => array('NEQ', 9)))
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                //优惠内容
                $list[$k]['coupon_info'] = "抵价".$v['money']."元";
                //已使用/已领取/总数
                $list[$k]['nums'] = $this->getDoNums($v['id']);
                //有效期
                $list[$k]['deadlinemode'] = $this->deadlinemode($v['id']);
                //发放渠道
                $list[$k]['channel'] = "通过优惠码";
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                /*处理数据*/
                $datas = [];
                $datas['title'] = $params['title'];//优惠码标题
                $datas['money'] = $params['money'];//优惠金额
                //生成数量必须在1～1000之间
                if($params['num'] >= 1 && $params['num'] <= 1000){
                    $num = $params['num'];
                }else{
                    $this->error('生成数量必须在1～1000之间');
                }

                //优惠码前缀是否重复
                $is_prefix = model('Coupon')->getPrefix($params['prefix']);

                if($is_prefix === false){
                    $datas['prefix'] = $params['prefix'];
                }else{
                    $this->error('优惠码前缀不正确或已使用');
                }

                //优惠码位数
                if($params['digits'] >= 5 && $params['digits'] <= 15){
                    $digits = $params['digits'];
                }else{
                    $this->error('优惠码位数必须在5～15位之间');
                }
                
                $datas['type'] = 1;

                //有效期类型
                $datas['deadlineMode'] = $params['deadlineMode'];
                
                if($params['deadlineMode']  == "time"){
                    $datas['deadline'] = strtotime($params['deadline']);
                }else{
                    $datas['fixedDay'] = $params['fixedDay'];
                }

                $datas['description'] = $params['description'];
                $datas['create_time'] = time();

                /*新增优惠码记录*/
                $result = false;
                try {
                    $result = $this->model->allowField(true)->insertGetId($datas);
                    if ($result !== false) {
                        /*循环生成优惠码*/
                        $this->couponaccountadd($result,$datas,$num,$digits);
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 查看优惠码详情列表
     */
    public function couponlist($ids = null)
    {
        $row = $this->model->get($ids)->toArray();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $list = model('CouponList')
        ->where('coupon_id', $ids)
        ->order('id', 'asc')
        ->paginate(10);

        foreach ($list as $k => $v) {
            //状态
            if($v['status'] == 0){
                $list[$k]['status_title'] = "未使用";
            }else if($v['status'] == 1){
                $list[$k]['status_title'] = "已使用";
            }else if($v['status'] == 2){
                $list[$k]['status_title'] = "已过期";
            }else if($v['status'] == 3){
                $list[$k]['status_title'] = "已删除";
            }

            //使用者
            $list[$k]['user_info'] = "-";
            //订单信息
            $list[$k]['order_info'] = "-";
            //领取时间
            $list[$k]['start_time'] = "-";
            //使用时间
            $list[$k]['use_time'] = "-";

        }

        $this->view->assign("list", $list);
        return $this->view->fetch();

    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', $ids)->update(['status' => '9','updatetime' => time()]);
        model('CouponList')->where('coupon_id', $ids)->update(['status' => '3']);
        $this->success();
    }

    /**
     * 循环生成优惠码
     */
    public function couponaccountadd($ids = "",$data = array(),$num = 0,$digits = 0)
    {

        $where = [];
        $where['coupon_id'] = $ids;
        $where['money'] = $data['money'];
        $where['user_type'] = "student";
        $where['create_time'] = time();
        $m = 0;
        for ($x=1; $x<=$num; $x++) {
            $where['coupon'] = $data['prefix'].$this->GetRandStr($digits);;
            $result = model('CouponList')->allowField(true)->insertGetId($where);
            if($result !== false){
                $m++;
            }
        }

        return $m;
    }


    /**
     * 计算优惠券使用情况
     */
    public function getDoNums($id = ''){

        if(empty($id)){
            return false;
        }

        /*查询优惠券详情*/
        $count = model('CouponList')->where('coupon_id', $id)->count();
        if ($count <= 0) {
            return false;
        }

        //领取
        $user_count = model('CouponList')->where('coupon_id', $id)->where(array('user_id' => array('NEQ', 0)))->count();

        //使用
        $do_count = model('CouponList')->where('coupon_id', $id)->where('status' , 1)->count();
        
        return $do_count."/".$user_count."/".$count;

    }

    
    /**
     * 计算优惠券有效期
     */
    public function deadlinemode($id = ''){

        if(empty($id)){
            return false;
        }

        $row = $this->model->get($id)->toArray();
        if (!$row) {
            return false;
        }

        if($row['deadlineMode'] == 'time'){
           
           $ret =  date('Y-m-d',$row['create_time'])." ~ ".date('Y-m-d',$row['deadline']);
            
        }else{
            $ret =  date('Y-m-d',$row['create_time'])." 至 领取后".$row['fixedDay']."天内";
        }
 
        return $ret;

    }


   /**
     * 生成随机码
     */
    public function GetRandStr($length){
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
        $num=mt_rand(0,$len);
        $randstr .= $str[$num];
        }
        return $randstr;
    }


}
